package com.hifar.test.checktemplate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.fw.utils.bean.BusiConst;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.test.checktemplate.constant.CheckTemplateConstant;
import com.hifar.test.checktemplate.pojo.HfEnvCheckTemplate;
import com.hifar.test.checktemplate.pojo.VO.HfEnvCheckTemplateVO;
import com.hifar.test.checktemplate.service.IHfEnvCheckTemplateItemService;
import com.hifar.test.checktemplate.service.IHfEnvCheckTemplateService;
import com.hifar.sys.*;
import com.hifar.validate.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 环境-检查模版 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-12 13:46:14
 */
@RestController
@RequestMapping("/api/busi/test/hfEnvCheckTemplateController")
@Api(tags = "环境-检查模版功能")
public class HfEnvCheckTemplateController {

    @Autowired
    private IHfEnvCheckTemplateService hfEnvCheckTemplateService;

    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private AutoLogUtils autoLogUtils;

    @PostMapping(value = "/list")
    @ApiOperation(value = "环境-检查模版功能:分页查询列表")
    public BusiResponse list(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        QueryWrapper<HfEnvCheckTemplate> queryWrapper = RequestConver.getPostParam(pageInfo);
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        if (queryWrapper != null && pageInfo.size() > 0) {
            Page<HfEnvCheckTemplate> page = new Page<>((Integer) pageInfo.get("pageNo"), (Integer) pageInfo.get("pageSize"));
            Page<HfEnvCheckTemplate> page1 = hfEnvCheckTemplateService.page(page, queryWrapper);
            /*计算分页信息返回给前端*/
            PageResult pageResult = SystemUtil.parsePage(page, page1);
            return BusiResponse.OK(pageResult);
        }else {
             return BusiResponse.error("参数不正确！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "环境-检查模版功能:查询列表(不带分页)")
    public BusiResponse listAll(HttpServletRequest request) {
        QueryWrapper<HfEnvCheckTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");
        queryWrapper.in("secret_level",SystemLoginUser.dataSecretSet);
        List<HfEnvCheckTemplate> list = hfEnvCheckTemplateService.list(queryWrapper);
        list.forEach(item->{
        });
        if (list != null && list.size() > 0) {
            return BusiResponse.OK(list);
        }else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "环境-检查模版功能:新增")
    public BusiResponse add(@RequestBody @Validated HfEnvCheckTemplateVO hfEnvCheckTemplateVO) {
        hfEnvCheckTemplateService.saveHfEnvCheckTemplate(hfEnvCheckTemplateVO);
        String checkName = hfEnvCheckTemplateVO.getCheckName();
        autoLogUtils.addLog("环境试验-检查模板", String.format("新增检查模板:【%s】", checkName));

        return BusiResponse.ok("添加成功");
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "环境-检查模版功能:编辑")
    public BusiResponse edit(@RequestBody @Validated(UpdateGroup.class) HfEnvCheckTemplateVO hfEnvCheckTemplateVO) {
        hfEnvCheckTemplateService.editHfEnvCheckTemplate(hfEnvCheckTemplateVO);
        String checkName = hfEnvCheckTemplateVO.getCheckName();
        autoLogUtils.modifyLog("环境试验-检查模板", String.format("编辑检查模板:【%s】", checkName));
        return BusiResponse.ok("编辑成功！");
    }


    @Autowired
    private IHfEnvCheckTemplateItemService  HfEnvCheckTemplateItemService;


    @GetMapping("/queryVOById")
    @ApiOperation(value = "环境-检查模版功能:根据id查询数据")
    public BusiResponse queryVOById(@RequestParam(value = "id") String id){
        HfEnvCheckTemplateVO byId = hfEnvCheckTemplateService.queryHfEnvCheckTemplateVO(id);
        /*
        //  获取主表id
        String  mainId = byId.getId();
        
        QueryWrapper<HfEnvCheckTemplateItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("del_flag", 1);
        queryWrapper.eq("CHECK_TEMPLATE_ID",mainId);
        List<HfEnvCheckTemplateItem> list = HfEnvCheckTemplateItemService.list(queryWrapper);
        // 保存子表
        if(list!=null) {
        	byId.setHfEnvCheckTemplateItemList(list);
        }
        */
        
        
        return BusiResponse.OK(byId);
    }


    @PostMapping(value = "/save")
    @ApiOperation(value = "环境-检查模版功能:新增")
    public BusiResponse save(@RequestBody @Validated HfEnvCheckTemplate hfEnvCheckTemplate) {
        String type = hfEnvCheckTemplate.getType();
        if (Objects.equals(type, CheckTemplateConstant.HANDOVER_TEMPLATE_TYPE)) {
            QueryWrapper<HfEnvCheckTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(HfEnvCheckTemplate::getType, type);
            int count = hfEnvCheckTemplateService.count(queryWrapper);
            Assert.isTrue(count <= 0, "交接班检查模板已添加!无法重复添加!");
        }
        hfEnvCheckTemplateService.save(hfEnvCheckTemplate);
        String checkName = hfEnvCheckTemplate.getCheckName();
        autoLogUtils.addLog("环境试验-检查模板", String.format("添加检查模板:【%s】", checkName));

        return BusiResponse.ok("添加成功");
    }





    @PostMapping(value = "/modify")
    @ApiOperation(value = "环境-检查模版功能:编辑")
    public BusiResponse modify(@RequestBody HfEnvCheckTemplate hfEnvCheckTemplate) {
        String type = hfEnvCheckTemplate.getType();
        String id = hfEnvCheckTemplate.getId();
        Assert.notNull(id, "id不能为空!");
        if (Objects.equals(type, CheckTemplateConstant.HANDOVER_TEMPLATE_TYPE)) {
            QueryWrapper<HfEnvCheckTemplate> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(HfEnvCheckTemplate::getType, type)
                    .ne(HfEnvCheckTemplate::getId, id);
            int count = hfEnvCheckTemplateService.count(queryWrapper);
            Assert.isTrue(count <= 0, "交接班检查模板已添加!无法重复添加!");
        }
        hfEnvCheckTemplateService.updateById(hfEnvCheckTemplate);
        String checkName = hfEnvCheckTemplate.getCheckName();
        autoLogUtils.modifyLog("环境试验-检查模板", String.format("编辑检查模板:【%s】", checkName));
        return BusiResponse.ok("编辑成功！");
    }




    @GetMapping("/queryById")
    @ApiOperation(value = "环境-检查模版功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id){
        HfEnvCheckTemplate byId = hfEnvCheckTemplateService.getById(id);
        // 查询转换附件
        return BusiResponse.OK(byId);
    }





    @PostMapping("/delete")
    @ApiOperation(value = "环境-检查模版功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfEnvCheckTemplate> templatesList = hfEnvCheckTemplateService.listByIds(idList);
        hfEnvCheckTemplateService.removeByIds(idList);
        String templateNames = templatesList.stream()
                .map(HfEnvCheckTemplate::getCheckName)
                .distinct()
                .collect(Collectors.joining(","));
        autoLogUtils.deleteLog("环境试验-检查模板", String.format("删除了检查模板:【%s】", templateNames));
        return BusiResponse.ok("删除成功！");
    }
   
    @PostMapping("/exportExcel")
	@ApiOperation(value = "环境-检查模版功能:导出数据")
	public Object exportExcel(HttpServletRequest request) {
		Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
		if (pageInfo == null) {
			return BusiResponse.error("参数有误！");
		}
		BusiResponse export = hfEnvCheckTemplateService.exportExcel(pageInfo);
		if (export.getCode() == BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("环境-检查模版.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            autoLogUtils.exportLog("环境试验-检查模板", "导出检查模板");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
		return export;
	}

	@PostMapping("/importExcel")
	@ApiOperation(value = "环境-检查模版功能:导入excel数据")
	public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
		if (file.isEmpty()) {
			return BusiResponse.error("文件为空！");
		} else {
			if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.importLog("环境试验-检查模板", "导入检查模板");
				return hfEnvCheckTemplateService.importExcel(file);
			} else {
				return BusiResponse.error("请上传excel文件！");
			}
		}
	}
    

}